package net.sunbeta.testng;

import java.net.URI;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerService;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class JmsHelper {
    private Session     session;
    private Destination destination;

    //  create jms from jndi
    /*   @BeforeClass(groups = "jms")
       public void setupJMS() throws NamingException, JMSException {
           Hashtable env = new Hashtable();
           InitialContext context = new InitialContext(env);
           ConnectionFactory factory = (ConnectionFactory) context.lookup("QueueConnectionFactory");
           Connection connection = factory.createConnection();
           session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
           destination = (Destination) context.lookup("TestQueue@router1");
       }*/

    // create jms from contenter  server
    @BeforeClass(groups = "jms")
    public void setupActiveMQ() throws Exception {
        BrokerService broker = new BrokerService();
        broker.setPersistent(false);
        broker.setUseJmx(false);
        broker.start();
        URI uri = broker.getVmConnectorURI();
        ConnectionFactory factory = new ActiveMQConnectionFactory(uri);
        //String uri = "vm://localhost?broker.persistent=false";
        //ConnectionFactory factory = new ActiveMQConnectionFactory(uri);
        Connection connection = factory.createConnection();
        connection.start();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        destination = session.createQueue("TestQueue@router1");
    }

    @Test(groups = "jms")
    public void sendMessage() throws JMSException {
        TextMessage msg = session.createTextMessage();
        msg.setText("hello");
        session.createProducer(destination).send(msg);
    }

    @Test(groups = "jms", dependsOnMethods = "sendMessage", timeOut = 1000)
    public void receiveMessage() throws JMSException {
        MessageConsumer consumer = session.createConsumer(destination);
        TextMessage msg = (TextMessage) consumer.receive();
        assert "hello".equals(msg.getText());
    }
}
